package com.xxxx.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxxx.server.config.security.component.JwtTokenUtil;
import com.xxxx.server.mapper.AdminMapper;
import com.xxxx.server.mapper.AdminRoleMapper;
import com.xxxx.server.mapper.RoleMapper;
import com.xxxx.server.pojo.Admin;
import com.xxxx.server.pojo.AdminRole;
import com.xxxx.server.pojo.Role;
import com.xxxx.server.service.IAdminService;
import com.xxxx.server.util.AdminUtil;
import com.xxxx.server.vo.RespBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 学海无涯
 * @since 2021-11-15
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private AdminMapper adminMapper;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private AdminRoleMapper adminRoleMapper;
    @Override
    public RespBean<Map<String, String>> login(String username, String password, String code, HttpServletRequest request) {
        // 登录
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        String captcha = (String) request.getSession().getAttribute("captcha");
        if (StringUtils.isBlank(captcha) || !captcha.equalsIgnoreCase(code)){
            return new RespBean<Map<String, String>>().error("验证码不正确！");
        }
        if (null == userDetails || passwordEncoder.matches(password,userDetails.getPassword())){
            return new RespBean<Map<String, String>>().error("用户名或密码不正确！");
        }
        if (!userDetails.isEnabled()){
            return new RespBean<Map<String, String>>().error("账号被禁用！");
        }
        // 更新登录用户对象
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
        // 将对象放在Security中
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        Map<String,String> tokenMap = new HashMap<>();
        // 生成token
        String token = jwtTokenUtil.generateToken(userDetails);
        tokenMap.put("token",token);
        tokenMap.put("tokenHead",tokenHead);
        return new RespBean<Map<String, String>>().success("登录成功",tokenMap);
    }

    @Override
    public Admin getAdminByUsername(String username) {
        return adminMapper.selectOne(new QueryWrapper<Admin>().eq("username",username).eq("enabled",true));
    }

    @Override
    public List<Role> getRoles(Integer adminId) {

        return roleMapper.getRoles(adminId);
    }

    @Override
    public List<Admin> getAllAdmins(String keywords) {
        return adminMapper.getAllAdmins(AdminUtil.getCurrentAdmin().getId(), keywords);
    }

    /**
     * 更新操作员角色
     * @param adminID
     * @param rIDs
     * @return
     */
    @Override
    @Transactional
    public RespBean updateAdminRole(Integer adminID, Integer[] rIDs) {
        adminRoleMapper.delete(new QueryWrapper<AdminRole>().eq("adminId",adminID));
        if (null == rIDs || 0 == rIDs.length){
            return new RespBean().success("更新成功！");
        }
        int count = adminRoleMapper.insertRecord(adminID,rIDs);
        if (count == rIDs.length){
            return new RespBean().success("更新成功！");
        }
        return new RespBean().error("更新失败！");
    }

    /**
     * 更新用户密码
     * @param oldPass 老密码
     * @param pass 新密码
     * @param adminId 用户id
     * @return
     */
    @Override
    public RespBean updateAdminPassword(String oldPass, String pass, Integer adminId) {
        Admin dbAdmin = adminMapper.selectById(adminId);
        // 密码加密类
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        // 验证旧密码
        if (encoder.matches(oldPass,dbAdmin.getPassword())){
            // 设置新密码
            dbAdmin.setPassword(encoder.encode(pass));
            int count = adminMapper.updateById(dbAdmin);
            if (1 == count){
                return new RespBean().success("更新成功");
            }
            return new RespBean().success("更新失败");
        }
        return new RespBean().error("旧密码输入不正确");
    }

    /**
     * 更新用户头像
     * @param url
     * @param adminId
     * @param authentication
     * @return
     */
    @Override
    public RespBean updateUserFace(String url, Integer adminId, Authentication authentication) {
        Admin admin = adminMapper.selectById(adminId);
        admin.setUserFace(url);
        int count = adminMapper.updateById(admin);
        if (1 == count){
            Admin principal = (Admin) authentication.getPrincipal();
            principal.setUserFace(url);
            SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(admin, null,authentication.getAuthorities()));
            return new RespBean().success("更新成功!",url);
        }
        return new RespBean().success("更新失败!");
    }
}
